package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/9 22:10
 */
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Autowired
    private CheckItemDao checkItemDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;


    /**
     *添加套餐的基本信息，和中间表的信息
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐的基本信息
        setmealDao.add(setmeal);
        if (setmeal.getSex() == null) {
            setmeal.setSex("0");
        }
        //向redis中添加保存到数据库中的图片的名称
        //判断当图片不为空时，才进行添加
        if (setmeal.getImg() != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES_DB, setmeal.getImg());
        }

        //添加中间表的信息
        Integer id = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addBySetmealidAndCheckgroupid(id, checkgroupId);
        }
        //生成静态页面
//        generateMobileStaticHtml();
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        //因为有外键所以先删除中间表的数据
        //删除套餐的中间表信息
        setmealDao.deleteById(id);
        //删除套餐的基本信息
        setmealDao.delete(id);
        //删除静态页面
        String path="D:\\project\\mei-health\\parent_health\\health_mobile\\src\\main\\webapp\\pages\\setmeal_detail_"+id+".html";
        File file = new File(path);
        if (file != null) {
            file.delete();
        }
        return true;
    }

    @Override
    @Transactional
    public boolean update(Setmeal setmeal,Integer[] checkgroupIds) {
        //修改检查套餐基本信息
        setmealDao.update(setmeal);

        //使用redis添加图片名称
        if (setmeal.getImg() != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES_DB, setmeal.getImg());
        }
        //通过检查套餐的id删除所有中间表的信息
        setmealDao.deleteById(setmeal.getId());
        //添加中间表的信息
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.addBySetmealidAndCheckgroupid(setmeal.getId(), checkgroupId);
        }
        return false;
    }

    /**
     * 根据条件查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult getByConditions(QueryPageBean queryPageBean) {
        //先分页
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //进行条件查询
        List<Setmeal> all=setmealDao.getByConditions(queryPageBean.getQueryString());
        PageInfo pageInfo = new PageInfo(all);
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }

    @Override
    public Setmeal getById(Integer id) {
        Setmeal setmeal=setmealDao.getById(id);
        return setmeal;
    }

    @Override
    public List<Integer> getCheckGroupIds(Integer id) {
        List<Integer> checkGroupIds=setmealDao.getCheckGroupIds(id);
        return checkGroupIds;
    }

    @Override
    public List<Setmeal> getAll() {
        return setmealDao.getAll();
    }

    /**
     * 通过id查询套餐及关联的检查组检查项的信息
     * @param id
     * @return
     */
    @Override
    public Setmeal getByIdMany(Integer id) {
        //通过id查询到套餐的基本信息
        Setmeal setmeal = setmealDao.getByIdMany(id);
        return setmeal;
    }

    @Override
    public List<Map<String, Object>> getSetmealNameAndOrdercount() {
//        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> list=setmealDao.getSetmealNameAndOrdercount();
        return list;
    }

    //获取静态页面
    public void generateMobileStaticHtml() {
        //从数据库中全部套餐信息
        List<Setmeal> list = setmealDao.getAll();
        //调用获取静态列表页面
        generateMobileSetmealListHtml(list);

        //循环遍历list从中获取套餐的id
        for (int i = 0; i < list.size(); i++) {
            Integer id = list.get(i).getId();
            //从数据库查询单个套餐的信息包括检查组和检查项
            Setmeal setmeal = setmealDao.getById(id);
            generateMobileSetmealDetailHtml(setmeal);
        }


    }

    //获取静态列表页面
    public void generateMobileSetmealListHtml(List list) {
        //将集合封装成map
        Map map = new HashMap();
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //获取静态详情页面
    public void generateMobileSetmealDetailHtml(Setmeal setmeal) {
        //将对象封装成map
        Map map = new HashMap();
        map.put("setmeal", setmeal);
        generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
    }


    //生成静态页面的基本模板
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        //加载模板所在的文件夹
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out=null;
        try {
            //获得模板对象
            Template template = configuration.getTemplate(templateName);
            //获取生成文件的输出流
            out = new FileWriter(new File(outPutPath+"\\"+htmlPageName));
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
